package com.namuan.jp_stock.activity;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.namuan.jp_stock.dialog.GuidePopupDialog;
import com.namuan.jp_stock.dialog.ImageViewDialog;
import com.namuan.jp_stock.util.AsyncJustplaceRunner;
import com.namuan.jp_stock.util.BaseRequestListener;
import com.namuan.jp_stock.util.Justplace;
import com.namuan.jp_stock.util.JustplaceError;
import com.namuan.jp_stock.util.SessionStore;
import com.namuan.jp_stock.util.Util;
import com.namuan.jp_stock.activity.LoginActivity;
import com.namuan.jp_stock.activity.MainActivity;
import com.namuan.jp_stock.activity.RegisterActivity;
import com.namuan.jp_stock.activity.LoginActivity.CntTimer;
import com.namuan.jp_stock.activity.LoginActivity.LoginRequestListener;
import com.namuan.jp_stock.R;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener{
	public static ArrayList<Activity> activityList = new ArrayList<Activity>();		
	Justplace mJustplace;
	EditText usernicknameText;
	EditText pwText;
	Button LoginBtn;
	Button RegistBtn;
	CheckBox autoLoginCk;
	boolean loginok =false;
	boolean boolCheckStop = false;
	private AsyncJustplaceRunner mAsyncRunner;		
	private boolean isTwoClickBack = false;
	private final int GUIDE_ACTIVITY = 1;
	

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        // 남아 있는 액티비티들 종료
        for(int i = 0 ; i < activityList.size(); i++) {
        	if(!activityList.get(i).isFinishing())
        		activityList.get(i).finish();
        }
        LoginBtn = (Button)findViewById(R.id.Loginbtn);
        RegistBtn = (Button)findViewById(R.id.Registbtn);
        autoLoginCk= (CheckBox)findViewById(R.id.autoLoginCk);
        ImageButton headerGuideBtn = (ImageButton) findViewById(R.id.headerGuideBtn);
        headerGuideBtn.setOnClickListener(this);
        TextView tvGuide = (TextView) findViewById(R.id.tvGuide);
        tvGuide.setOnClickListener(this);
        LoginBtn.setOnClickListener(this);
        RegistBtn.setOnClickListener(this);
        usernicknameText = (EditText)findViewById(R.id.usernicknameText);
		pwText = (EditText)findViewById(R.id.pwText);
		
		TextView tvAccountGuide = (TextView) findViewById(R.id.tvAccountGuide);
		tvAccountGuide.setText("Please send e-mail to ");
		tvAccountGuide.append( Html.fromHtml("<font color=\"blue\"><u>" + "justplace@namuan.com " + "</font></u>") );
		tvAccountGuide.append("when you forget your password or have problems.");

		tvGuide.setText(Html.fromHtml("<font color=\"black\"><u>" + "서비스 안내 " + "</font></u>") );

		//Please send e-mail to justplace@namuan.com when you forget your password or have problems.
		
		mJustplace=new Justplace();
		mAsyncRunner=new AsyncJustplaceRunner(mJustplace);
		SessionStore.restore(mJustplace, this);
		
		
		
		if(mJustplace.ismAutologin()){
			Intent Insert_intent = new Intent(this, MainActivity.class);
			Insert_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
			this.startActivity(Insert_intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			finish();
		}
		
		if(!mJustplace.ismCheckPopup()){
			/*
			AlertDialog.Builder dialog = new AlertDialog.Builder(LoginActivity.this);	
			dialog.setMessage("위치정보 활용에 동의 하시겠습니까?");
			dialog.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {										
							
						}
					});
			dialog.setNegativeButton("No",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int which) {
							dialog.dismiss();
							
						}
					});
			dialog.show();
			*/
			/*
			String url = "app_introduction.png";
			Intent guide_intent = new Intent(this, GuidePopupDialog.class);
			guide_intent.putExtra("imageurl", url);
			this.startActivityForResult(guide_intent, GUIDE_ACTIVITY);
			*/
		} else
			boolCheckStop = true;
    }
    
	@Override
	public void onClick(View v) {
		switch(v.getId())
		{
		
		// get Tweets ��ư Ŭ��
		case R.id.Loginbtn:
			
			mAsyncRunner.login(usernicknameText.getText().toString(), pwText.getText().toString(),new LoginRequestListener(), null);
			break;
		
		// set ListView ��ư Ŭ��
		case R.id.Registbtn:
			Intent Insert_intent = new Intent(this, RegisterActivity.class);
			this.startActivity(Insert_intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			break;
			
		// refresh ��ư Ŭ��
		case R.id.userHeaderNickname:
		
			break;
		case R.id.headerGuideBtn:
			Intent guide_intent = new Intent(this, ImageViewDialog.class);
			String url = "service_using_guid_page.png";
			guide_intent.putExtra("imageurl", url);
			this.startActivity(guide_intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			break;
			
		case R.id.tvGuide:
			Intent guide_intent1 = new Intent(this, ImageViewDialog.class);
			String url1 = "service_using_guid_page.png";
			guide_intent1.putExtra("imageurl", url1);
			this.startActivity(guide_intent1);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			break;
			
		}
		
		
		
	}
	 @Override
	 protected void onActivityResult(int requestCode, int resultCode, Intent data){
		 super.onActivityResult(requestCode, resultCode, data); 
		 if(resultCode == RESULT_OK && data != null){
			 switch(requestCode){
			 case  GUIDE_ACTIVITY:
				 boolCheckStop = data.getBooleanExtra("boolCheckStop", true);
				 break;
			 }
		 }
	 }
public class LoginRequestListener extends BaseRequestListener {
	@Override
	public void onIOException(IOException e, Object state) {
		// TODO Auto-generated method stub
		super.onIOException(e, state);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Util.showAlert(LoginActivity.this, "로그인실패", "통신상태를 확인해 주세요");
			}

		});
	}

	public void onComplete(final String response, final Object state) {

		try {
			JSONObject json = Util.parseJson(response);
			Log.d("json", json.get("state") + "");
			if (json.getBoolean("state")) {
				SessionStore.clear(LoginActivity.this);
				Log.d("SESSSION!!!!!!!!", json.get("session").toString());
				mJustplace.setmSession(json.get("session").toString());
				mJustplace.setmUserNickname(json.get("usernick").toString());
				mJustplace.setmProfilepic(json.get("profilepic").toString());
				mJustplace.setmCheckPopup(boolCheckStop);
				if (autoLoginCk.isChecked()) {
					mJustplace.setmAutologin(true);
				} else {
					mJustplace.setmAutologin(false);
				}
				loginok = true;
			}
		} catch (JSONException e) {

			e.printStackTrace();
		} catch (JustplaceError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				if (loginok) {
					loginSuccess();
				} else {
					loginFail();
				}
			}
		});
	}
}
	public void loginSuccess(){
		SessionStore.save(mJustplace, this);
		Intent Insert_intent = new Intent(this, MainActivity.class);
		this.startActivity(Insert_intent);
		overridePendingTransition(R.anim.fade, R.anim.hold);
		finish();
	}
	public void loginFail(){
		Util.showAlert(LoginActivity.this, "로그인실패", "아이디와 패스워드를 확인해주세요");
	}
	class CntTimer extends CountDownTimer {
		public CntTimer(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
			isTwoClickBack = true;
		}

		@Override
		public void onFinish() {
			// TODO Auto-generated method stub
			isTwoClickBack = false;
		}

		@Override
		public void onTick(long millisUntilFinished) {
			// TODO Auto-generated method stub
			//Log.i("Test", " isTwoClickBack " + isTwoClickBack);
		}

	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				if (!isTwoClickBack) {
					Toast.makeText(this, "'뒤로'버튼을 한번 더 클릭하시면 종료됩니다.",
							Toast.LENGTH_SHORT).show();
					CntTimer timer = new CntTimer(2000, 1);
					timer.start();
				} else {
					finish();
					return true;
				}

			}
		}
		return false;
	}		
}
